package com.xuebank.nfe.nfecar

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.os.SystemClock
import android.provider.MediaStore
import android.support.design.widget.BottomNavigationView
import android.text.TextUtils
import android.view.KeyEvent
import android.webkit.CookieManager
import android.webkit.CookieSyncManager
import android.widget.LinearLayout
import android.widget.Toast
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.wzn.libaray.utils.Logger
import com.wzn.libaray.utils.cache.SharedPreferencesUtil
import com.xuebank.nfe.nfecar.activity.CameraActivity
import com.xuebank.nfe.nfecar.activity.WelcomeActivity
import com.xuebank.nfe.nfecar.beas.BaseActivity
import com.xuebank.nfe.nfecar.beas.BaseFragment
import com.xuebank.nfe.nfecar.fragment.FindFragment
import com.xuebank.nfe.nfecar.fragment.HomeFragment
import com.xuebank.nfe.nfecar.fragment.MineFragment
import com.xuebank.nfe.nfecar.globals.Constants
import com.xuebank.nfe.nfecar.utils.bridge.BridgeWebView
import com.xuebank.nfe.nfecar.utils.buttonnavigation.BottomNavigationViewEx
import com.xuebank.nfe.nfecar.utils.buttonnavigation.BottomNavigationViewHelper
import android.util.TypedValue.COMPLEX_UNIT_DIP
import android.util.TypedValue.applyDimension
import android.support.design.internal.BottomNavigationMenuView
import android.util.TypedValue
import com.madai.eazyloan.globals.PERMISSION_LAUCH
import com.xuebank.nfe.nfecar.activity.SecondActivity
import com.xuebank.nfe.nfecar.fragment.NewsFragment
import com.xuebank.nfe.nfecar.utils.AlertModel
import com.xuebank.nfe.nfecar.utils.IntentUtil
import com.xuebank.nfe.nfecar.utils.PermissionUtil


class MainActivity : BaseActivity(){
    private var mPattern: Boolean = false
    private var isFirstSetupDone = false

    private var last_show_TAB: Int = R.id.home
    private var back_pressed: Long = 0
    private lateinit var navigation: BottomNavigationViewEx
    private var mUrl: String? = null
    private var abdge : LinearLayout? = null
    private var homeFragment:HomeFragment?=null
    var bitmap: Bitmap? = null
    var intent1: Intent? = null
    var mPushIntentParameter :String ? = null
    var bundle :Bundle? = null
    var myapplication:MyApplication? = null


    //导航条的监听时间
    private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
        if (item.itemId == last_show_TAB)
            return@OnNavigationItemSelectedListener false

        when (item.itemId) {
            R.id.home, R.id.find, R.id.news,R.id.mine -> {
                showFragment(item.itemId, last_show_TAB)
                last_show_TAB = item.itemId
            }
            R.id.new_add ->{
                val islongin = SharedPreferencesUtil.getInstance(this).getString(IS_LONGIN)
                val cookie = SharedPreferencesUtil.getInstance(this).getString(COOKIE)
                if (!TextUtils.isEmpty(islongin)&&islongin.contains("1") && cookie != null) {
                    CameraActivity.setUp(this)
                } else {
                    val intent = Intent(this, SecondActivity::class.java)
                    intent.putExtra("url",Constants.LOGIN_ADDRESS)
                    startActivity(intent)
                }
            }
        }
        true
    }



    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        /**
         * 微信分享
         */

        wx_api = WXAPIFactory.createWXAPI(this,Constants.WECHAT_APP_ID)
        wx_api?.registerApp(Constants.WECHAT_APP_ID)

        start_APP()
        checkLauchPermission()
    }
    fun checkLauchPermission() {
        PermissionUtil.checkPermmission(this,
                AlertModel(getString(R.string.common_request_permission_title),
                        getString(R.string.common_request_permission_cancel),
                        getString(R.string.common_request_permission_ok),
                        getString(R.string.lauch_request_permission_message)),
                object : PermissionUtil.OnPermissionResultListener {
                    override fun onPermissionGranted() {

                    }

                    override fun onPermissionGrantCancel() {
                        finish()
                        System.exit(2)
                    }

                    override fun onPermissionGrantSet() {
                        startActivityForResult(IntentUtil.gotoSystemSetting(this@MainActivity), PERMISSION_LAUCH)
                    }
                }
                , android.Manifest.permission.CAMERA
                , android.Manifest.permission.READ_PHONE_STATE
                , android.Manifest.permission.RECORD_AUDIO
                , android.Manifest.permission.ACCESS_FINE_LOCATION
                , android.Manifest.permission.WRITE_EXTERNAL_STORAGE
        )
    }

    //显示fragment
    fun showFragment(showTab: Int, hideTab: Int) {
        val fragmentTransaction = supportFragmentManager.beginTransaction()
        val showFragment = getMenuFragment(showTab)
        if (null != showFragment) {
            if (!showFragment.isAdded) {

                fragmentTransaction.add(R.id.main_content, showFragment, showFragment.TAG)

            }
            if (showTab != hideTab) {
                val hideFragment = getMenuFragment(hideTab)
                fragmentTransaction.hide(hideFragment).show(showFragment)

            } else {

                fragmentTransaction.show(showFragment)
            }

            fragmentTransaction.commitAllowingStateLoss()
        }
    }

    //导航条添加fragment
    fun getMenuFragment(tab: Int): BaseFragment {
        var baseMainMenuFragment: BaseFragment? = null
        val fragment: BaseFragment?
        val tag: String


        when (tab) {
            R.id.home -> {
                tag = "appay"
                fragment = supportFragmentManager.findFragmentByTag(tag) as? BaseFragment
                if (null != fragment) {
                    baseMainMenuFragment = fragment
                } else {

                    homeFragment= HomeFragment()
                    baseMainMenuFragment = homeFragment
                }
            }
            R.id.find -> {
                tag = "check"
//                mUrl = "https://awakenuat-cxs.jujinpan.cn/#h5/view/entry_idCard"
                fragment = supportFragmentManager.findFragmentByTag(tag) as? BaseFragment
                if (null != fragment) {
                    baseMainMenuFragment = fragment
                } else {
                    baseMainMenuFragment = FindFragment()
                }
            }
            R.id.news ->{
                tag = "news"
                fragment = supportFragmentManager.findFragmentByTag(tag) as? BaseFragment
                if (null != fragment) {
                    baseMainMenuFragment = fragment
                } else {
                    baseMainMenuFragment = NewsFragment()
                }

            }
            R.id.mine -> {
                tag = "more"
                fragment = supportFragmentManager.findFragmentByTag(tag) as? BaseFragment
                if (null != fragment) {
                    baseMainMenuFragment = fragment
                } else {
                    baseMainMenuFragment = MineFragment()
                }
            }

            else -> tag = ""
        }
        baseMainMenuFragment?.TAG = tag
        return baseMainMenuFragment!!
    }



    override fun initData(savedInstanceState: Bundle?) {
        super.initData(savedInstanceState)

    }


    internal var isFirstAAA = false


    override fun onResume() {
        super.onResume()
        if (isFirstSetupDone)
            super.onResume()
        else
            super.onResume(true)
    }

    override fun onPostResume() {
        super.onPostResume()
        if (isFirstSetupDone) {
            super.onPostResume()
            isFirstAAA = true

            if (isFirstAAA) {
                getMenuFragment(last_show_TAB).onHiddenChanged(true)
            }
            isFirstAAA = true

        } else {
            super.onPostResume(true)
        }
    }

    override fun onPause() {
        super.onPause()
        if (isFirstSetupDone) {
            super.onPause()
            getMenuFragment(last_show_TAB).onHiddenChanged(true)
        } else {
            super.onPause(true)
        }
    }

    //选中item的下标
    fun setCurrentTab(itemId: Int) {
        navigation.selectedItemId = itemId
    }
    private fun handleIntent(intent: Intent?) {
        if (null != intent) {
            when (intent.action) {
                TAB_CHECKED -> {
                    when (intent.getIntExtra(TAB_INDEX, 1)) {
                        1 ->
                            setCurrentTab(R.id.home)
                        2 ->
                            setCurrentTab(R.id.find)
                        3 ->
                            setCurrentTab(R.id.mine)
                    }
                }
            }
        }
    }


    fun start_APP() {
        if (isFirstSetup()) {
            if (intent.hasExtra(Constants.ACTION_EXIT_APP)) {
                isFirstSetupDone = false
                finish()
            } else {
                firstSetup()
            }
        } else {
            mThisActivity()
        }
    }

    //启动欢迎页面
    private fun firstSetup() {
        isFirstSetupDone = false

        val intent = Intent()
        val action = getIntent().action
        if (!TextUtils.isEmpty(action))
            intent.action = action
        intent.replaceExtras(getIntent())
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        intent.setClass(this, WelcomeActivity::class.java)
        startActivity(intent)
        this.finish()
    }

    fun mThisActivity() {
        isFirstSetupDone = true
        setContentView(R.layout.activity_main)
        firstInit()
        handleIntent(intent)//todo  onNewIntent

    }


    private fun firstInit() {

        val navigation = myFindViewById<BottomNavigationViewEx>(R.id.main_navigation)
//        if (mStationName.contains(guest) || mStationName.contains(group)) {
        navigation.inflateMenu(R.menu.navigation)
        navigation.setIconSize(25f,25f)
        navigation.setTextVisibility(false)//设置文字隐藏
        navigation.itemIconTintList = null//暴露出h图标本来的颜色

//        } else {
//            navigation.inflateMenu(R.menu.navigation)
//        }
        BottomNavigationViewHelper.disableShiftMode(navigation)
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
        navigation.selectedItemId = R.id.home
        showFragment(R.id.home, R.id.home)
    }

    companion object {
       public var wx_api:IWXAPI? = null

        val IS_LONGIN = "IS_LONGIN"



        val TAB_INDEX = "TAB_INDEX"
        val TAB_CHECKED = "TAB_CHECKED"
        val COOKIE = "COOKIE"
        val CHOOSING_ALBUMS = "CHOOSING_ALBUMS"//选择相册RxBus需要的常量

        val PHOTOGRAPH="PHOTOGRAPH"
        val VIDEO="VIDEO"

        var mianActivity :MainActivity? = null
        private val TAG = "MainActivity"

        var DEVELOPMENT_ENVIRONMENTs = ""
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit()
            return false
        }
        return super.onKeyDown(keyCode, event)

    }

    //连续点击两次back键的时间小于2000ms就退出app
    private fun exit() {
        if (back_pressed + 2000 > System.currentTimeMillis()) {
            exitApp()
        } else {
            Toast.makeText(this,R.string.exit_tips,Toast.LENGTH_SHORT).show()
//            ToastHelper.getInstance().showToast(R.string.exit_tips)
            back_pressed = System.currentTimeMillis()
        }
    }
    // 退出app
    fun exitApp() {
        Logger.d(TAG, "退出APP")
        finish()
        System.exit(0)
    }




    private fun isFirstSetup(): Boolean {
        var flag = true
        val type = intent.type
        val flags = intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY
        if (flags != Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY
                && !TextUtils.isEmpty(type) && type == Constants.ACTION_DO_FIRST_INIT) {
            flag = false
            Logger.d(TAG, "不进行初始化")
        }

        return flag
    }
}
